import axios from 'axios'
import store from "../store";
import {getToken, removeToken} from "./auth";
import { Toast } from 'vant';
import router from "../router";
import Vue from "vue";
import baseURL from "./baseURLConfig";

Vue.prototype.$axios = axios

const request = axios.create({
    // baseURL: 'http://192.168.129.100:8700/',
    baseURL: baseURL,
    timeout: 10000
})

request.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 请求拦截器
request.interceptors.request.use(config => {
    if (store.getters.token) {
        //请求需携带token
        config.headers['Authorization'] = getToken();
    }
    return config;
}, function (error) {
    return Promise.reject(error);
})


// 响应拦截器
request.interceptors.response.use(response => {
    const res = response.data
    if (res.code !== 200){
        if (res.code === 401){
            console.log('为登录')
        }
    }else {
        return response;
    }
}, error => {
    const resp = error.response.data
    if (resp.code === 401){
        Toast.fail(resp.msg);
        setTimeout(() => {
            store.dispatch('FedLogOut').then(r => {
                router.push('/login');
                removeToken();
            })

        }, 3000)
    }
    return Promise.reject(error);
})

// GET
export function get(url, params) {
    return new Promise(
        (resolve, reject) => {
            request.get(url, {params: params})
                .then(res => {
                    resolve(res.data)
                }).catch(err => {
                reject(err.data)
            })
        }
    )
}

// POST
export function post(url, data) {
    return new Promise(
        (resolve, reject) => {
            request.post(url, data)
                .then(res => {
                    // console.log('post请求封装res',res)
                    resolve(res.data)
                }).catch(err => {
                reject(err.data)
            })
        }
    )
}

// DELETE
export function del(url, params) {
    return new Promise(
        (resolve, reject) => {
            request.delete(url, params)
                .then(res => {
                    // console.log('delete请求封装res',res)
                    resolve(res.data)
                }).catch(err => {
                reject(err.data)
            })
        }
    )
}

// PUT
export function put(url, data) {
    return new Promise(
        (resolve, reject) => {
            request.put(url, data)
                .then(res => {
                    // console.log('put请求封装res',res)
                    resolve(res.data)
                }).catch(err => {
                reject(err.data)
            })
        }
    )
}

export default request;
